package com.azt.front.action.product;

import com.alibaba.fastjson.JSON;
import com.azt.api.dto.ProductData;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.exception.BaseException;
import com.azt.front.action.BaseAction;
import com.azt.front.permission.RequireCompany;
import com.azt.front.permission.RequireProvider;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.Globals;
import com.azt.model.AjaxJson;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequireCompany
@RequestMapping("/product")
public class ProductAction extends BaseAction {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProCategoryService categoryService;

    @Autowired
    private ProCategoryBrandService categoryBrandService;

    @Autowired
    private ProCategoryAttributeService categoryAttributeService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private IntegralService integralService;

    @Autowired
    private CompanyService companyService;

    @RequireProvider
    @RequestMapping("/list")
    public String list(Model model) {
        Integer tab = getParaToInt("tab", 1);
        tab = tab == null ? 1 : tab;
        String keyword = getParaTrim("keyword");
        int pageSize = Globals.PAGESIZE;
        int pageNo = getParaToInt("pageNo", 1);   //页码
        Integer companyId = ContextUtil.getCompanyId();

        Integer ifPub = 1;
        String state = "1";
        switch (tab) {
            case 2:
                //待审核
                state = "0,3";
                break;
            case 3:
                //已下架
                ifPub = 0;
                break;
            case 4:
                //未通过审核
                state = "2";
        }

        Map param = new HashMap();
        param.put("ifPub", ifPub);
        param.put("state", state);
        param.put("keyword", keyword);
        param.put("companyId", companyId);
        param.put("pageSize", pageSize);

        PageHelper.startPage(pageNo, pageSize);
        List<Map> list = productService.searchProduct(param);

        model.addAttribute("param", WebUtils.getParametersStartingWith(request, null));
        model.addAttribute("tab", tab);
        //待审核的商品数量
        model.addAttribute("auditCount", productService.getAuditProductCount(companyId));
        model.addAttribute("data", new PageInfo(list));
        return "product/list";
    }

    @RequestMapping("/choose")
    public String choose() {
        return "product/choose";
    }

    @RequireProvider
    @RequestMapping("/chooseCate")
    public String chooseCate(Model model) {
        model.addAttribute("companyExt", companyService.getCompanyExtByCustomerid(ContextUtil.getCompanyId()));
        return "product/chooseCate";
    }

    /**
     * 载入发布/更新商品页面
     * */
    @RequireProvider
    @RequestMapping(value = "/publish", method = RequestMethod.GET)
    public String loadPublish(Model model) {
        Integer productId = getParaToInt("productId");      //更新的商品id
        Integer cateId = getParaToInt("cateId");            //发布商品时的类别id

        if(productId == null && cateId == null) {
            return "redirect:/product/chooseCate";
        }

        if(productId != null) {
            //更新商品
            Product product = productService.getProductById(productId);
            if(product == null || product.getCustomerId() == null || product.getCustomerId().intValue() != ContextUtil.getCompanyId().intValue()) {
                return "redirect:/product/chooseCate";
            }
            cateId = product.getCategoryTId();

            model.addAttribute("product", product);
        }

        if(cateId != null) {
            //分类
            Map cates = categoryService.getParentCates(cateId);
            //所属品牌
            List<Brand> brandList = categoryBrandService.findBrandByCategoryId(1, null, null, null, cateId);
            //商品属性(已经包含了属性值)
            List<ProCategoryAttribute> attributeList = categoryAttributeService.getProCategoryAttributes(cateId);
            List<ProCategoryAttribute> rtnAttrList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(attributeList)) {
                for(ProCategoryAttribute attr : attributeList) {
                    if(attr != null && StrUtil.isNotBlank(attr.getItemStr()) && !"[]".equals(attr.getItemStr())) {
                        rtnAttrList.add(attr);
                    }
                }
            }


            model.addAttribute("cates", cates);
            model.addAttribute("brandList", brandList);
            model.addAttribute("attrList", rtnAttrList);
        }

        //单位
        model.addAttribute("unitList", dictService.getDictionByParentCode("PRO_UNIT"));
        model.addAttribute("companyExt", companyService.getCompanyExtByCustomerid(ContextUtil.getCompanyId()));
        return "product/publish";
    }

    /**
     * 获取商品的sku信息
     * */
    @ResponseBody
    @RequestMapping(value = "/listSku", method = RequestMethod.POST)
    public AjaxJson listSku() {
        Integer productId = getParaToInt("productId");

        if(productId != null) {
            Map map = new HashMap();
            List<ProSku> skuList = productService.findProSkuByProId(productId);
            if(CollectionUtil.isNotEmpty(skuList)) {
                if(skuList.size() == 1 && StrUtil.isEmpty(skuList.get(0).getSku())) {
                    //没有独立商品
                    ProductData.SkuData skuData = new ProductData.SkuData();
                    skuData.setSkuId(skuList.get(0).getId());
                    skuData.setPrice(skuList.get(0).getPrice());
                    skuData.setMemberPrice(skuList.get(0).getMemberPrice());
                    skuData.setChangeStock(skuList.get(0).getStockQuantity());
                    map.put("alone", true);
                    map.put("data", skuData);
                    return AjaxJson.success().setObj(map);
                } else {
                    List<Map> list = new ArrayList<>();
                    List<ProSkuAttr> fstProSkuAttrList = null;
                    for(ProSku proSku : skuList) {
                        List<ProSkuAttr> proSkuAttrList = productService.findSkuAttrBySkuId(proSku.getId());
                        if(fstProSkuAttrList == null) {
                            fstProSkuAttrList = proSkuAttrList;
                        }

                        Map m = new HashMap();
                        m.put("skuId", proSku.getId());
                        m.put("price", proSku.getPrice());
                        m.put("memberPrice", proSku.getMemberPrice());
                        m.put("changeStock", proSku.getStockQuantity());
                        m.put("sku", proSku.getSku());
                        List<ProductData.SkuData.SkuAttr> skuAttrList = new ArrayList<>();
                        for(ProSkuAttr proSkuAttr : proSkuAttrList) {
                            ProductData.SkuData.SkuAttr skuAttr = new ProductData.SkuData.SkuAttr();
                            skuAttr.setName(proSkuAttr.getName());
                            skuAttr.setValue(proSkuAttr.getValue());
                            skuAttr.setNameId(proSkuAttr.getNameId());
                            skuAttr.setValueId(proSkuAttr.getValueId());
                            skuAttrList.add(skuAttr);
                        }
                        m.put("skuAttrList", skuAttrList);
                        list.add(m);
                    }
                    StringBuilder options = new StringBuilder();
                    for(ProSkuAttr proSkuAttr : fstProSkuAttrList) {
                        options.append(proSkuAttr.getNameId()).append(",");
                    }
                    if(options.toString().endsWith(",")) {
                        options = options.deleteCharAt(options.length() - 1);
                    }
                    map.put("alone", false);
                    map.put("options", options);
                    map.put("data", list);
                    return AjaxJson.success().setObj(map);
                }
            }
        }
        return AjaxJson.error();
    }

    @ResponseBody
    @RequireCompany
    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public AjaxJson publish() {
        try {
            ProductData productData = BeanUtil.requestParamToBean(request, ProductData.class, true);
            List<ProductData.SkuData> skuList = JSON.parseArray(getParaTrim("skuList"), ProductData.SkuData.class);
            productData.setSkuList(skuList);
            Company company = ContextUtil.getCompany();
            productData.setUserId(ContextUtil.getUserId());
            productData.setCompanyId(company.getId());
            productData.setIfSelf(company.getIfSelf());
            productService.publishProduct(productData);
        } catch (BaseException be) {
            return AjaxJson.error(be.getErrorCode());
        } catch (Exception e) {
            LOGGER.error("publish product error", e);
            return AjaxJson.error("操作失败");
        }
        return AjaxJson.success();
    }

    /**
     * 删除商品规格组合
     * */
    @RequireCompany
    @ResponseBody
    @RequestMapping(value = "/removeProSku", method = RequestMethod.POST)
    public AjaxJson removeProSku() {
        Integer skuId = getParaToInt("skuId");

        if(skuId != null) {
            productService.removeProSku(skuId);
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }

    /**
     * 商品上下架
     * */
    @RequireCompany
    @ResponseBody
    @RequestMapping(value = "/upDownProduct", method = RequestMethod.POST)
    public AjaxJson upDownProduct() {
        String productIds = getParaTrim("productId");
        Integer type = getParaToInt("type");        //1. 上架  2. 下架

        if(StrUtil.isNotBlank(productIds) && type != null && (type == 1 || type == 2)) {
            String[] array = productIds.split(",");
            List<Integer> productIdList = new ArrayList<>();
            for(String str : array) {
                Integer productId = Convert.toInt(str);
                if(productId != null) {
                    productIdList.add(productId);
                }
            }
            productService.upDownProduct(productIdList, type == 1 ? true : false);
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }

    @RequireCompany
    @ResponseBody
    @RequestMapping(value = "/removeProduct", method = RequestMethod.POST)
    public AjaxJson removeProduct() {
        String productIds = getParaTrim("productId");

        if(StrUtil.isNotBlank(productIds)) {
            String[] array = productIds.split(",");
            List<Integer> productIdList = new ArrayList<>();
            for(String str : array) {
                Integer productId = Convert.toInt(str);
                if(productId != null) {
                    productIdList.add(productId);
                }
            }
            productService.removeProduct(productIdList);
            return AjaxJson.success();
        }
        return AjaxJson.error();
    }
    
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success() {
    	return "product/success";
    }
}
